package com.jbp.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.model.RoomUserWheat;
import com.jbp.model.User;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.AgoraService;
import com.jbp.service.RoomUserWheatService;
import com.jbp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**声网监控
 * */
@Component
@Configuration
public class AgoraJob {

    @Autowired
    private RoomUserWheatService roomUserWheatService;

    @Autowired
    private AgoraService agoraService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisConfigService redisConfigService;

    /**
     * 踢出非法用户
     */
    @Scheduled(fixedDelay = 1000)
    public void quitRoom(){
        if (redisConfigService.setLock("agora_kick", 20)){
            List<RoomUserWheat> list = roomUserWheatService.notEmptyRooms();
            List<Integer> bugs = new ArrayList<>();
            if (list != null) {
                for (RoomUserWheat roomUserWheat : list) {
                    List<Integer> ids = agoraService.getUsers(roomUserWheat.getRoomId());
                    if (ids != null) {
                        for (Integer id : ids) {
                            RoomUserWheat one = roomUserWheatService.getOne(new QueryWrapper<RoomUserWheat>()
                                    .eq("room_id", roomUserWheat.getRoomId())
                                    .eq("user_id", id)
                            );
                            if (one == null) {
                                User user = userService.getById(id);
                                if (user == null || (user.getLevel() == 0 && user.getUuid().length() >= 8)) {
//                            if (user==null) {
                                    bugs.add(id);
                                    agoraService.addRule(id);
                                }
                            }
                        }

                    }
                }
            }
            if (!bugs.isEmpty()) {
                System.out.println("踢人:" + bugs);
            }
        }
    }



}
